<template>
    <div>
        <van-tree-select height="88.6vh" :items="tabItems" :main-active-index.sync="active" @click-nav="selectShopTab">
            <template #content>
                <lazy-component>
                    <div style="text-align: left" v-for="(item,index) in commoditys" :key="index">
                        <div v-show="typeCode == item.commodityCode">
                            <van-card
                                    :price="item.price/100"
                                    :desc="item.desc"
                                    :title="item.title"
                                    :origin-price="item.originPrice/100"
                                    :thumb="item.imgUrl"
                                    @click-thumb="clickThumb(item.imgUrl)"
                                    :tag="item.stockNumStr"
                            >
                                <template #tags>
                                    <van-tag plain type="danger" v-for="(tag,id) in item.vanTag.split(';')" :key="id">{{tag}}</van-tag>
                                </template>
                                <template v-if="item.stockNum !== 0" #footer>
                                    <van-stepper v-model="item.num" min="0" theme="round" button-size="20" disable-input/>
                                </template>
                            </van-card>
                        </div>
                    </div>
                </lazy-component>
            </template>
        </van-tree-select>

        <van-submit-bar :price="totalPrice" :disabled="showSubmitDis" :button-text="onSubmitDesc" @submit="onSubmit">
            <template #tip>
                <van-notice-bar
                    :text="circular"
                    left-icon="volume-o"
                    scrollable
                    color="#1989fa"
                    background="#ecf9ff"
                />
            </template>
            <van-goods-action-icon icon="cart-o" text="购物车" :badge="shoppingCartNum" @click="shoppingCartClick" />

            <van-goods-action-icon icon="description-o" text="我的订单"  @click="onClickRight" />

            <van-goods-action-icon icon="edit" text="建议箱"  @click="onClickProposal" />
        </van-submit-bar>

        <van-dialog v-model="show" :before-close="beforeClose" title="提交订单" show-cancel-button>
            <br/>
            <van-cell-group>
                <van-field
                        v-model="form.order.phone"
                        required
                        maxlength="11"
                        label="手机号"
                        placeholder="请输入手机号"
                        @change="phoneChang"
                />
                <van-field
                        readonly
                        clickable
                        required
                        name="picker"
                        :value="value"
                        label="选择器"
                        placeholder="点击选择城市"
                        @click="showPicker = true"
                />
                <van-field
                        v-model="form.order.remarks"
                        rows="2"
                        autosize
                        label="留言"
                        type="textarea"
                        maxlength="50"
                        placeholder="请输入留言"
                        show-word-limit
                />
            </van-cell-group>
        </van-dialog>

        <van-popup v-model="showPicker" position="bottom">
            <van-picker
                    show-toolbar
                    :columns="columns"
                    @confirm="onConfirm"
                    @cancel="showPicker = false"
                    @change="pickerChange"
            />
        </van-popup>

        <van-popup class="custom-popup-bg" v-model="showShoppingCart" position="top" :style="{ height: '80%' }">
            <div style="text-align: left;margin: 20px 10px" v-for="(item,index) in commoditys" :key="index">
                <div v-show="item.num > 0">
                    <van-card
                            :price="item.price/100"
                            :desc="item.desc"
                            :title="item.title"
                            :origin-price="item.originPrice/100"
                            :thumb="item.imgUrl"
                    >
                        <template #tags>
                            <van-tag plain type="danger" v-for="(tag,id) in item.vanTag.split(';')" :key="id">{{tag}}</van-tag>
                        </template>
                        <template #footer>
                            <van-stepper v-model="item.num" min="0" theme="round" button-size="20" disable-input @plus="onPlusStepper(item)"/>
                        </template>
                    </van-card>
                </div>
            </div>
        </van-popup>

        <van-overlay :show="overlayShow"/>

        <van-popup class="custom-popup-bg" v-model="orderShow" position="top" :style="{ height: '80%' }">
            <div style="text-align: left;margin: 20px 10px " v-for="(item,index) in orderList" :key="index">
                <van-collapse v-model="activeNames" accordion @change="collapseChange(item)">
                    <van-collapse-item :name="index">
                        <template #title>
                            <div>
                                <span>{{item.orderCode}}</span>
                                <span style="float: right">
                                    <van-tag v-if="item.status === 0" round type="warning">{{item.statusStr}}</van-tag>
                                    <van-tag v-if="item.status === 1" round type="primary">{{item.statusStr}}</van-tag>
                                    <van-tag v-if="item.status === 2" round color="#7232dd">{{item.statusStr}}</van-tag>
                                    <van-tag v-if="item.status === 3" round type="success">{{item.statusStr}}</van-tag>
                                    <van-tag v-if="item.status === 4" round type="danger">{{item.statusStr}}</van-tag>
                                </span>
                            </div>
                        </template>
                        <div>

                            <van-steps v-if="item.status !== 4" :active="item.status">
                                <van-step>已下单</van-step>
                                <van-step>已接单</van-step>
                                <van-step>配送中</van-step>
                                <van-step>已完成</van-step>
                            </van-steps>
                            <div v-for="(desc,key) in orderDescList" :key="key">
                                <van-card
                                        :price="(desc.price/100)"
                                        :desc="desc.desc"
                                        :title="desc.title"
                                        :origin-price="desc.originPrice/100"
                                        :thumb="desc.imgUrl"
                                        :num="desc.num"
                                >
                                    <template #tags>
                                        <van-tag plain type="danger" v-for="(tag,id) in desc.vanTag.split(';')" :key="id">{{tag}}</van-tag>
                                    </template>
                                </van-card>
                            </div>
                        </div>
                    </van-collapse-item>
                </van-collapse>
            </div>
        </van-popup>

        <van-dialog v-model="orderDialogShow" title="输入手机查看订单" show-cancel-button @confirm = "dialogConfirmShowOrder">
            <br/>
            <van-cell-group>
                <van-field
                        v-model="form.order.phone"
                        required
                        label="手机号"
                        maxlength="11"
                        placeholder="请输入手机号"
                />
            </van-cell-group>
        </van-dialog>

        <van-dialog v-model="proposalDialogShow" title="匿名建议信" show-cancel-button @confirm = "dialogConfirmShowProposal">
            <br/>
            <van-cell-group>
                <van-field
                        v-model="proposal"
                        rows="4"
                        label="建议信："
                        type="textarea"
                        maxlength="500"
                        placeholder="请输入您宝贵得建议"
                        show-word-limit
                />
            </van-cell-group>
        </van-dialog>
    </div>
</template>

<script>
    import { ImagePreview } from 'vant'
    import { Notify } from 'vant';
    import { Toast } from 'vant';
    import { useTitle } from '@vueuse/core';
    export default {
        name: "ShopList",
        data() {
            return {
                form: {
                    order:{
                        communityCode:"",
                        address:"",
                        totalAmount:"",
                        phone:"",
                        remarks:""
                    },
                    orderDescList:""
                },
                typeCode:"",
                overlayShow:false,
                show: false,
                active: 0,
                proposal: null,
                commoditys:[],
                stepper: 0,
                shoppingCartNum:0,
                showShoppingCart: false,
                value: '',
                showPicker: false,
                tabItems: [],
                columns: [],
                totalPrice:0,   //总价格
                orderShow:false,
                orderDialogShow:false,
                proposalDialogShow:false,
                orderDescList:[],
                orderList:[],
                activeStep: 1,
                activeNames: "",
                regions:{},
                onSubmitDesc:"",
                minimumDeliveryPrice:0,
                showSubmitDis:true,
                circular:null,
                communityCode:""
            };
        },
        watch: {
            // 监听整个myObject对象的变化
            commoditys: {
                handler() {
                    var totalPrice = 0
                    var shoppingCartNum = 0
                    var flg = true
                    this.commoditys.forEach(cart => {
                        totalPrice = totalPrice + (cart.price * cart.num);
                        shoppingCartNum = shoppingCartNum + cart.num
                        if(cart.num != 0){
                            flg = false
                        }
                    })
                    if(flg){
                        this.showShoppingCart = false
                    }
                    this.totalPrice = totalPrice
                    if(this.totalPrice == 0){
                        this.showSubmitDis = true
                        this.onSubmitDesc = "￥" + (this.minimumDeliveryPrice/100) + "起送"

                    } else if(this.totalPrice < this.minimumDeliveryPrice){
                        this.onSubmitDesc = "差￥"+ ((this.minimumDeliveryPrice - this.totalPrice)/100) + "起送"
                        this.showSubmitDis = true
                    } else if(this.totalPrice >= this.minimumDeliveryPrice){
                        this.onSubmitDesc = "去结算"
                        this.showSubmitDis = false;
                    }
                    this.shoppingCartNum = shoppingCartNum
                    this.tabItems.forEach(tab => {
                        tab.badge = null
                        this.commoditys.forEach(cart => {
                            if(tab.code == cart.commodityCode && cart.num > 0){
                                tab.badge = tab.badge + cart.num
                            }
                        })
                    })
                },
                deep: true // 开启深度监听
            }
        },
        methods: {
            phoneChang(){
                const regex = /^1[3-9]\d{9}$/;
                const isValid = regex.test(this.form.order.phone);
                if(!isValid){
                    Notify({ type: 'warning', message: "请输入正确的电话号码" });
                } else {
                    this.$axios.getPhoneAddress({phone:this.form.order.phone}).then(res => {
                        console.log(res.data.data == {})
                        this.value = res.data.data
                    })
                }

            },
            clickThumb(item){
                ImagePreview({
                    images:[item],
                    closeable: true,
                });
            },
            beforeClose(action, done){
                if (action === "confirm") { // 点击确定走这里
                    let list = [];
                    this.commoditys.forEach(cart =>{
                        if(cart.num > 0){
                            list.push(cart)
                        }
                    })
                    if(list.length == 0){
                        Notify({ type: 'warning', message: "请先选择商品" });
                        done(true)
                        return;
                    }
                    if(this.form.order.phone == ''){
                        Notify({ type: 'warning', message: "请输入手机号" });
                        done(false)
                        return;
                    }
                    const regex = /^1[3-9]\d{9}$/;
                    const isValid = regex.test(this.form.order.phone);
                    if(!isValid){
                        Notify({ type: 'warning', message: "请输入正确的电话号码" });
                        done(false)
                        return;
                    }
                    if(this.value == ''){
                        Notify({ type: 'warning', message: "请选择地址" });
                        done(false)
                        return;
                    }
                    this.form.order.communityCode = this.commoditys[0].communityCode
                    this.form.order.address = this.value
                    this.form.order.totalAmount = this.totalPrice


                    this.form.orderDescList = list
                    this.overlayShow = true;
                    this.$axios.insertOrder(this.form).then(res => {
                        this.overlayShow = false;
                        var ordercode = res.data.data.orderCode;
                        this.commoditys.forEach(item => {
                            item.num = 0
                        })
                        done(true)
                        Toast.success("订单提交成功");
                        Notify({ type: 'success', message: '订单已提交【'+ordercode+'】' });
                        this.form.order.remarks = "";
                        this.value = "";
                    }).catch(msg => {
                        Notify({ type: 'danger', message: msg.message });
                        done(false)
                        this.overlayShow = false;
                    })
                } else { // 点击取消走这里
                    done(true) // 关闭弹窗, true可以省略
                }
            },
            selectShopTab(item){
                var indexTab = this.tabItems[item]
                this.typeCode = indexTab.code
            },
            onSubmit() {
                this.show = true;
            },
            onConfirm(value) {
                this.value = value
                    .filter((item) => item)
                    .map((item) => item)
                    .join('-');
                this.showPicker = false;
            },
            shoppingCartClick(){
                let flg = true
                this.commoditys.forEach(cart =>{
                    if(cart.num > 0){
                        flg = false;
                        this.showShoppingCart = true;
                        return;
                    }
                })
                if(flg){
                    Notify({ type: 'warning', message: "您还未选择商品，请先选择商品" });
                }
            },
            dialogConfirmShowOrder(){
                const regex = /^1[3-9]\d{9}$/;
                const isValid = regex.test(this.form.order.phone);
                if(!isValid){
                    Notify({ type: 'warning', message: "请输入正确的电话号码" });
                } else {
                    const toast = Toast.loading({
                        message: '加载中...',
                        forbidClick: true,
                        loadingType: 'spinner',
                        duration: 0
                    });
                    this.$axios.orderList({phone:this.form.order.phone}).then(res => {
                        this.orderList = res.data.data
                        toast.clear();
                        if(this.orderList.length != 0){
                            this.orderShow = true;
                        } else {
                            Notify({ type: 'warning', message: '没有找到该手机号相关的订单' });
                        }
                    })
                }

            },
            dialogConfirmShowProposal(){
                const toast = Toast.loading({
                    message: '加载中...',
                    forbidClick: true,
                    loadingType: 'spinner',
                    duration: 0
                });
                if(this.proposal != null && this.proposal != ""){
                    this.$axios.proposal({desc:this.proposal,communityCode:this.communityCode}).then(res => {
                        console.log(res)
                        toast.clear();
                        this.proposalDialogShow = false;
                        Notify({ type: 'warning', message: '感谢您提的宝贵建议' });
                    })
                } else {
                    this.proposalDialogShow = true;
                    Notify({ type: 'warning', message: '建议信不能为空' });
                }
            },


            onClickRight() {
                this.orderDialogShow = true;
            },
            onClickProposal() {
                this.proposalDialogShow = true;
            },
            collapseChange(item) {
                const toast = Toast.loading({
                    message: '加载中...',
                    forbidClick: true,
                    loadingType: 'spinner',
                    duration: 0
                });
                this.$axios.orderDescList({orderCode:item.orderCode}).then(res => {
                    this.orderDescList = res.data.data
                    toast.clear();
                })
            },
            pickerChange(picker, values){
                let str = values[0]
                let strList = this.regions[str]
                this.columns = [{ values: Object.keys(this.regions)}]
                for(let i = 0; i< strList.length; i++){
                    this.columns.push(strList[i])
                }
            },
        },

        created(){
            const toast = Toast.loading({
                message: '加载中...',
                forbidClick: true,
                loadingType: 'spinner',
                duration: 0
            });
            // TODO 获取商品类型
            let region = window.location.search.replace("?region=","");
            if(region.trim() == null || region.trim() == undefined || region.trim() == ""){
                Notify({ type: 'warning', message: "抱歉，没有获取到区域信息。请扫描二维码查看" });
            } else {
                this.communityCode = region
                this.$axios.getCommodityTypeList({"communitycode":region}).then(res =>{
                    this.tabItems = res.data.data;
                    var indexTab = this.tabItems[0];
                    this.form.order.communityCode = indexTab.communityCode
                    this.typeCode = indexTab.code
                    this.$axios.commodityList({"commodityCode":indexTab.code,"communityCode":indexTab.communitycode}).then(res => {
                        this.commoditys = res.data.data
                        toast.clear();
                    })
                }).catch(error => {
                    console.log(error)
                })

                this.$axios.getRegion({"codeType":region}).then(res => {
                    this.regions = res.data.data.address
                    this.minimumDeliveryPrice = res.data.data.minimumDeliveryPrice
                    this.circular = res.data.data.circular
                    let index = Object.keys(this.regions)
                    var indexItem = ""
                    index.forEach(item => {
                        indexItem = indexItem + "-" + item
                    })
                    useTitle(indexItem.slice(1))
                    this.columns = [{ values: Object.keys(this.regions)}]
                    this.regions[index[0]].forEach(item =>{
                        this.columns.push(item)
                    })
                }).catch(error => {
                    console.log(error)
                })
            }

        },
    }
</script>

<style scoped>
    .custom-popup-bg {
        background-color: #f7f8fa;
    }
    .popup-submit {
        margin-top: 30px;
        margin-right: 20px;
        margin-left: 20px;
    }
    .van-submit-bar__tip{
        padding: 0px;
    }
</style>